<?php
namespace Maowenke\PersonalWechatSdk\applet;
use Maowenke\PersonalWechatSdk\Wecate;
use think\facade\Cache;

class WecateApplet extends Wecate
{
    protected $url = 'https://api.weixin.qq.com/';

    /**获取openid
     * @param string $code
     * @return bool|null
     */
    public function getOpenId(string $code='',$key='openid'){
        if(empty($code)){
            return false;
        }
        $bool = $this->verification();
        if(!$bool){
            return $bool;
        }
        $url = $this->url."sns/jscode2session?appid={$this->getCofnig('appid')}&secret={$this->getCofnig('secret')}&js_code=$code&grant_type=authorization_code";
        $array = $this->curl->http_requests($url,[],[],'GET');
        if(is_array($array)){
            if($key==false){
                return $array;
            }
            return $array[$key]??'';
        }else{
            $this->message = $array;
            return false;
        }
    }

    /**通过code获取用户手机号码
     * @param string $code
     * @return false|mixed
     */
    public function getUserPhone(string $code){
        $access_token = $this->getAppletAccessToken(false);
        if(empty($code)||empty($access_token)){
            $this->message = '没有code或者access_token';
            return false;
        }
        $url = $this->url."wxa/business/getuserphonenumber?access_token=$access_token";
        $data = [
//            'access_token'=>$access_token,
            'code'=>$code,
        ];
//        echo '<pre>';
//        print_r($data);
//        exit;
        $data = json_encode($data);
        $header = [
            "Content-Type: application/json",
            "Content-Length: " . strlen($data) . "",
        ];
        $array = $this->curl->http_requests($url,$data,$header,'POST');
//        echo "<pre>";
//        print_r($array);
//        exit;
        if(isset($array['errcode'])&&$array['errcode']==0){
            return $array['phone_info']['phoneNumber'];
        }else{
            $this->message = $array['errmsg']??'未返回数据';
            return false;
        }
    }
    public function getAppletAccessToken($refresh=false){
        $appid = $this->config['appid']??$this->config['app_id']??'';
        if(empty($appid)){
            $this->message = '没有设置appid';
            return false;
        }
        if($refresh){
            $url = $this->url."cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$this->getCofnig('secret')}";
            $array = $this->curl->http_requests($url,[],[],"GET");
            if(isset($array['access_token'])&&$array['access_token']){
                Cache::set('getAppletAccessToken'.$appid,$array,$array['expires_in']-1);
                return $array['access_token'];
            }else{
                return false;
            }
        }
        $array = Cache::get('getAppletAccessToken'.$appid);
        if(empty($array)){
            $url = $this->url."cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$this->getCofnig('secret')}";
            $array = $this->curl->http_requests($url,[],[],"GET");
            if(isset($array['access_token'])&&$array['access_token']){
                Cache::set('getAppletAccessToken'.$appid,$array,$array['expires_in']-100);
                return $array['access_token'];
            }else{
                return false;
            }
        }
        return $array['access_token'];
    }

    /**获取session
     * @param string $code
     * @return array|bool|string|null openid|session_key
     */
    public function jscode2session(string $code){
        if(empty($code)){
            return false;
        }
        $bool = $this->verification();
        if(!$bool){
            return $bool;
        }
        $url = $this->url."sns/jscode2session?appid={$this->getCofnig('appid')}&secret={$this->getCofnig('secret')}&js_code=$code&grant_type=authorization_code";
        $array = $this->curl->http_requests($url,[],[],'GET');
        if(is_array($array)){
            if(isset($array['errcode'])){
                $this->message = 'errmsg';
                return false;
            }
            return $array;
        }else{
            $this->message = $array;
            return false;
        }
    }

    /**
     * @param $session_key
     * @param $encryptedData
     * @param $iv
     * @return false|string
     */
    public function decryptData( $session_key,$encryptedData, $iv )
    {
        if (strlen($session_key) != 24) {
            return false;
        }
        $aesKey=base64_decode($session_key);
        if (strlen($iv) != 24) {
            return false;
        }
        $aesIV=base64_decode($iv);
        $aesCipher=base64_decode($encryptedData);
        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            $this->message = '解密失败';
            return false;
        }
        if( $dataObj->watermark->appid != $this->getCofnig('appid'))
        {
            $this->message = 'appid不正确';
            return false;
        }
        $data = json_decode($result,true);
        if(isset($data['errcode'])){
            $this->message = $data['errmsg']??'未返回信息';
            return false;
        }
        if(isset($data['phoneNumber'])||isset($data['purePhoneNumber'])){
            $data['phone'] = $data['phoneNumber']??$data['purePhoneNumber'];
        }
        return $data;
    }
    /**获取小程序的类目
     * @return false|mixed
     */
    public function getCategory(){
        $access_token = $this->getAppletAccessToken();
        if(!$access_token){
            $this->message = '获取access_token失败';
            return false;
        }
        $url = $this->url.'wxaapi/newtmpl/getcategory?access_token='.$access_token;
        $array = $this->curl->http_requests($url,[],[],"GET");
//        dump($array);die();
//        echo '<pre>';
//        print_r($array);
//        exit;
        if(isset($array['errcode'])&&$array['errcode']==0){
            return $array['data'];
        }else{
            $this->message = $array['errmsg']??'未返回信息';
            return false;
        }
    }

    /**获取小程序的Generate
     * @param $url
     * @param false $is_permanent
     * @return false|mixed
     */
    public function getGenerate($url,$is_permanent=false){
        $access_token = $this->getAppletAccessToken();
        $nurl = $this->url."wxa/genwxashortlink?access_token={$access_token}";
        $data = [
//            'access_token'=>$access_token,
            'page_url'=>$url,
            'page_title'=>'升林人力资源',
            'is_permanent'=>$is_permanent,
        ];
//        $data['sign'] = $this->getSign($data);
//        echo '<pre>';
//        print_r($nurl);
//        exit;
        $array = $this->curl->http_requests($nurl,$data,[]);
        if(isset($array['errcode'])&&$array['errcode']==0){
            return $array['link'];
        }else{
            $this->message = $array['errmsg']??'未返回数据';
            return false;
        }
    }

    /**
     * @param $url
     * @param $query
     * @param string $env_version
     * @param int $expire_time
     * @param bool $is_expire
     * @return false|mixed
     */
    public function getGeneratesCheme($url,$query,$env_version='release',$expire_time=2,$is_expire=true){
        $access_token = $this->getAppletAccessToken(true);
        $nurl = $this->url."wxa/generatescheme?access_token={$access_token}";
        $data = [
            'jump_wxa'=>[
                "path"=>$url,
                "query"=>$query,
                "env_version"=>$env_version,
            ],
//            'access_token'=>$access_token,
//            'page_url'=>$url,
//            'page_title'=>'升林人力资源',
            "is_expire"=>$is_expire,
            "expire_time"=>time()+(86400*$expire_time)
        ];
//        $data['sign'] = $this->getSign($data);
//        echo '<pre>';
//        print_r($nurl);
//        exit;
        $array = $this->curl->http_requests($nurl,$data,[]);
//        echo '<pre>';
//        print_r($array);
//        exit;
        if(isset($array['errcode'])&&$array['errcode']==0){
            return $array['openlink'];
        }else{
            $this->message = $array['errmsg']??'未返回数据';
            return false;
        }
    }

    /**获取微信小程序的分享链接
     * @param $url
     * @param $query
     * @param string $env_version
     * @param bool $is_expire
     * @param int $expire_type
     * @param int $expire_interval
     * @return false|mixed
     */
    public function getGenerateUrllink($url,$query,$env_version='release',$is_expire=true,$expire_type=1,$expire_interval=2){
        $access_token = $this->getAppletAccessToken(true);
        $nurl = $this->url."wxa/generate_urllink?access_token={$access_token}";
        $data = [
            'path'=>$url,
            'query'=>$query,
            "is_expire"=>$is_expire,
            'env_version'=>$env_version,
            "expire_type"=>$expire_type,
            "expire_interval"=>$expire_interval
        ];
//        $data['sign'] = $this->getSign($data);
//        echo '<pre>';
//        print_r($nurl);
//        exit;
        $array = $this->curl->http_requests($nurl,$data,[]);
//        echo '<pre>';
//        print_r($array);
//        exit;
        if(isset($array['errcode'])&&$array['errcode']==0){
            return $array['url_link'];
        }else{
            $this->message = $array['errmsg']??'未返回数据';
            return false;
        }
    }
    public function getUnlimited($openid,$page,$scene,$env_version='release'){
        if(!is_dir(root_path().'public'.DIRECTORY_SEPARATOR.'chengxuma')){
            @mkdir(root_path().'public'.DIRECTORY_SEPARATOR.'chengxuma');
        }
        if(is_file(root_path().'public'.DIRECTORY_SEPARATOR.'chengxuma'.DIRECTORY_SEPARATOR.$openid.'.jpg')){
            return '/chengxuma/'.$openid.'.jpg';
        }
        $access_token = $this->getAppletAccessToken(false);
        $nurl = $this->url."wxa/getwxacodeunlimit?access_token={$access_token}";
        $data = [
            'scene'=>$scene,
            'page'=>$page,
            'check_path'=>false,
            'env_version'=>$env_version,
        ];
        $str = json_encode($data);
        $header = [
            "Content-Type: application/json",
            "Content-Length: " . strlen($str) . "",
        ];
//        echo "<pre>";
//        print_r($nurl);
//        exit;
        $array = $this->curl->http_requests($nurl,$str,$header,'POST',false,false);

        $bool = file_put_contents(root_path().'public'.DIRECTORY_SEPARATOR.'chengxuma'.DIRECTORY_SEPARATOR.$openid.'.jpg',$array);
        if($bool==0){
            return false;
        }
        return '/chengxuma/'.$openid.'.jpg';
    }
}